<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\model\Menu;
use app\common\model\Role;
use app\common\tool\Result;
use think\facade\Cache;
use think\facade\View;
use think\Response;

class Index extends Base
{
    protected array $sort = [];

    public function index(): string
    {
        $rules = '';
        if ($this->admin['role_id'] != 1) {
            $rules = (new Role())->where('id', $this->admin['role_id'])->value('rules');
        }
        View::assign([
            'menus'      => Menu::getNewMenu(1, $rules),
            'attachMenu' => $this->admin['role_id'] == 1 ? Builder::TableCache()->getAttachMenu() : []
        ]);

        return View::fetch();
    }

    public function welcome(): string
    {
        View::assign([
            'server_name' => $_SERVER['SERVER_NAME']
        ]);

        return View::fetch();
    }

    public function clearCache(): Response
    {
        deldir('download/');

        return Cache::clear() ? Result::success('已清除') : Result::fail('加载失败');
    }

    public function getSetting(): Response
    {
        $result = [
            'btn_style' => cache('btn_style') ?: 1,
            'layout'    => cache('layout') ?: 1,
        ];

        return Result::success('success', $result);
    }

    public function setSetting(): Response
    {
        try {
            $param = $this->request->post();
            cache($param['key'], $param['value']);

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success('设置成功，刷新页面后生效');
    }
}